package com.origin.chaos.framework.core;

import com.origin.chaos.framework.core.util.ImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 图片推送到本地文件系统
 *
 * @author: tao.ding
 * @date 2021-07-02
 */
@Slf4j
public class LocalImagePusher implements ImagePusher {
    private static final String FILE_TYPE = "png";

    /**
     * 图片RGB像素数据数组
     */
    private int[][] imageRgbData;

    /**
     * 图片路径
     */
    private String filePathName;

    public LocalImagePusher(int[][] imageRgbData, String filePathName) {
        Assert.notNull(imageRgbData, "图片数据不能为空");
        Assert.isTrue(!ObjectUtils.isEmpty(filePathName), "本地文件路径不能为空");
        Assert.isTrue(filePathName.endsWith("." + FILE_TYPE), "仅支持" + FILE_TYPE + "类型的本地图片推送");
        this.imageRgbData = imageRgbData;
        this.filePathName = filePathName;
    }

    @Override
    public void push() {
        // 输出图片
        try {
            long st1 = System.currentTimeMillis();
            BufferedImage image = ImageUtil.getBufferedImage(this.imageRgbData);
            ImageIO.write(image, FILE_TYPE, new File(this.filePathName));
            long st2 = System.currentTimeMillis();
            log.debug("推送本地文件[" + this.filePathName + "]耗时" + (st2 - st1) + "ms");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
